#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>

struct point
{
	short x,y;
};

point s[500];
int sl,i,spd=200,score=0,plus;
point food,newh;

void gotoxy(short x, short y) 
{
	COORD pos = {x, y};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}


void drawh(int x, int y)// ve dau ran
{
	gotoxy(x,y);
	printf("%c",2);
}

void drawb(int x, int y)
{
	gotoxy(x,y);
	printf("%c",1);
}

void del(int x, int y)
{
	gotoxy(x,y);
	printf(" ");
}

void createfood()
{	short t=0,j;
	do
	{
		food.x=rand()%30;
		food.y=rand()%10;
		for(j=0;j<sl;j++)
	  		if ((s[j].x==food.x) && (s[j].y==food.y)) 
			  {
			  	t=1;
			  	break;
			  }
	}
	while (t==1);
	gotoxy(food.x,food.y);		
	printf("%c",3)  ;
	  
	
}
void create()
{
	sl=3;
	s[0].x=8;
	s[0].y=10;
	s[1].x=9;
	s[1].y=10;
	s[2].x=10;
	s[2].y=10;
	drawb(s[0].x,s[0].y); // create heard
	drawb(s[1].x,s[1].y); // create body
	drawh(s[2].x,s[2].y);
	createfood(); // khoi tao food ban dau
}
int kt() // kt da an food chua?
{	int tg;
	if ((food.x==newh.x) && (food.y==newh.y)) tg=1;
	else tg=0;
	return tg;
}
int keepon()//kt khi bam esc
{   int k;
	char key;
	gotoxy(1,20);
	printf("PAUSE!\n");
	printf("Are you sure you want to quit?\n");
	printf("Yes(Y) or No (N) : ");
	do
		scanf("%c",&key);
	while ((key!='y') && (key!='n')) ;
	if (key=='y')  k=0;
	if (key=='n')  k=1;
	return k;
}	
void run()
{
	unsigned char c;
	short x=10,y=10;
	int Huong = 3;
 do
 {
	do
	{
		Sleep(spd);//toc do, do kho
		if (kbhit())
		{
			c = getch();
			if (c==224)
			{
				c = getch();
				if (c==72) Huong=1;//up
				if (c==75) Huong=2;//left
				if (c==77) Huong=3;//right
				if (c==80) Huong=0;//down
			}
		}
		
		if (Huong==1) {newh.y=s[sl-1].y-1; newh.x=s[sl-1].x;}   //thay doi toa do dau
		if (Huong==2) {newh.x=s[sl-1].x-1; newh.y=s[sl-1].y;}
		if (Huong==3) {newh.x=s[sl-1].x+1; newh.y=s[sl-1].y;}
		if (Huong==0) {newh.y=s[sl-1].y+1; newh.x=s[sl-1].x;}
		
		drawb(s[sl-1].x,s[sl-1].y);
		drawh(newh.x,newh.y);
		if (kt()==1)
		{
			createfood();
			score=score+plus;
			sl++;
			//tinh diem
		}
		else
		{
			del(s[0].x,s[0].y); //xoa diem cuoi
			for (i=0;i<sl-1;i++) //chuyen toa do len
			 	s[i]=s[i+1];
		}
			s[sl-1]=newh;
	}
	while (c!=27); 
	c=20; // gan lai bien c bat ki
	}
	while (keepon()==1); // kt co tiep tuc khi bam esc
}

main()
{	
	srand(time(NULL));
	create();
	run();
	
}
